#####
# GENERAL HELPER FUNCTIONS
#####

# Removes extension
## fname = name of file to remove extension
## compressed = if want to also remove any extension with .gz or .zip
## replace = if you want to replace the extension with something specific
rmext = function(fname, compressed=T, replace="") {
    if (compressed==T)
        fname = sub("(.gz|.zip)$", replace, fname)
    fname = sub("\\.[^.]+$", replace, fname)
    return(fname)
}

# Get absolute path
abspath <- function(path) {
    dpath <- dirname(path)
    bpath <- basename(path)
    orig_path <- getwd()
    setwd(dpath)
    new_path <- file.path(getwd(), bpath)
    setwd(orig_path)
    return(new_path)
}

# Creates an empty matrix/array with same dimensions
empty = function(some.var, default.val=NA) {
	array(default.val, dim(some.var))
}

# Get lower half of matrix
lower = function(mat) {
	mat[lower.tri(mat)]
}

# Get upper half of matrix
upper = function(mat) {
	mat[upper.tri(mat)]
}

# Save lower half of vector to both halves of matrix
vec2mat = function(vec, mat, set.diag=NA) {
	# Set lower half
	mat[lower.tri(mat)] = vec
	# Set upper half
	mat[upper.tri(mat)] = upper(t(mat))
	# Set diagonal
	diag(mat) = set.diag

	return(mat)
}

# Fisher z transform
r2z = function(cor.mat) {
	atanh(cor.mat)
}

# Reverse transform
z2r = function(cor.mat) {
	tanh(cor.mat)
}

# Get z-score of subjects cor array
r2standard = function(cor.elem) {
	# Setup input
	if (is.matrix(cor.elem)) {
		tmp.vec = lower(cor.elem)
	} else if (is.vector(cor.elem)) {
		tmp.vec = cor.elem
	} else {
		stop("input must be a vector or matrix", "\n")
	}
	
	# Find any NAs
	tmp.na = na.action(na.omit(tmp.vec))
	
	# Convert
	if(is.null(tmp.na)) {
		tmp.vec = (tmp.vec - mean(tmp.vec))/sd(tmp.vec)
	} else {
		tmp.vec2 = tmp.vec[-tmp.na]
		tmp.vec2 = (tmp.vec2 - mean(tmp.vec2))/sd(tmp.vec2)
		tmp.vec[-tmp.na] = tmp.vec2
	}
	
	# Feedback
	if (is.matrix(cor.elem))
		return(vec2mat(tmp.vec, cor.elem))
	else
		return(tmp.vec)
}


# Demean a vector
demean = function(vec) {
	vec-mean(vec)
}

# Demean each column in a matrix
demean.mat = function(mat) {
	apply(mat, 2, z.demean)
}

# Normalize a vector
normalize = function(vec) (vec-mean(vec))/sd(vec)

# Normalize a matrix (by columns)
normalize.mat = function(mat) apply(mat, 2, z.normalize)

# Progress bar (convert this into some class)
create.progressbar = function(limit) txtProgressBar(min=0, max=limit, style=3)
update.progressbar = function(pb, i) setTxtProgressBar(pb, i)
end.progressbar = function(pb) { cat("\n"); close(pb) }

# FFT Wrapper
nifft = function(vec, Fs, to.plot=F) {
    N = length(vec) # Get number of points
    k = 0:(N-1)     # Create vector from 0 to N-1
    T = N/Fs        # Get the frequency interval
    freq = k/T      # Create the frequency range
    X = fft(vec)/N  # Normalize the data

    # Only want the first half of the FFT, since the rest is redundant
    cutOff = ceiling(N/2)
    X = X[1:cutOff];
    freq = freq[1:cutOff];
    
    # Plot if asked
    if (to.plot)
        plot(freq[-1], Mod(X[-1]), type='l', xlab="Frequency (Hz)", ylab="Power")
        
    return(list(fft=X, freq=freq))
}